package com.gulimall.seckill.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.fastjson2.JSONObject;
import com.gulimall.common.core.domain.Result;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.PrintWriter;

import static com.gulimall.common.enums.BizCodeEnum.REQUEST_TOO_FAST;

@Configuration
public class SentinelConfig {

    @Bean
    public BlockExceptionHandler blockExceptionHandler() {
        return (request, response, e) -> {
            response.setContentType("application/json;charset=UTF-8");
//            response.setStatus(HttpServletResponse.SC_TOO_MANY_REQUESTS); // 429 Too Many Requests
            Result<String> fail = Result.fail(REQUEST_TOO_FAST.getCode(),REQUEST_TOO_FAST.getDesc());
            try (PrintWriter writer = response.getWriter()) {
                writer.write(JSONObject.toJSONString(fail));
                writer.flush();
            }
        };
    }
}
